using System;
using System.IO;
using System.Threading.Tasks;

using MyFrame.Single;

using MyPlugin.Lua;

using UnityEngine;

using XLua;

namespace MyFrame.Lua
{
    /// <summary>
    /// 用于获取lua全局函数
    /// 返回值用out接收
    /// </summary>
    [CSharpCallLua]
    public delegate int CustomDelegate(int a, out int b);

    /// <summary>
    /// 执行lua
    /// </summary>
    public class LuaMgr : Singleton<LuaMgr>
    {
        public const string luaPath = "/Lua/";

        private LuaEnv luaEnv;
        public LuaTable Global => luaEnv.Global;

        public void Init()
        {
            if (luaEnv != null) return;
            luaEnv = new LuaEnv();
            //加载lua脚本，重定向  
            //依次执行没有找到会找默认路径
            luaEnv.AddLoader(MyCustomLoader);
            luaEnv.AddLoader(MyCustomLoaderAB);
        }


        
        /// <summary>
        /// 自定义加载
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private byte[] MyCustomLoader(ref string filePath)
        {
            // lua所在路径
            // string fullPath = Application.dataPath + luaPath + filePath + ".lua";
            string path = GetLuaFilePath(luaPath, filePath); ;

            if (File.Exists(path))
            {
                return File.ReadAllBytes(path);
            }
            else
            {
                Debug.Log("MyCustomLoader重定向失败" + path);
            }
            return null;

            string GetLuaFilePath(string luaPath, string filePath)
            {
                string relativePath = Path.Combine(luaPath, filePath + ".lua");
                string fullPath = Application.dataPath + relativePath;
                return Path.GetFullPath(fullPath); // 解析 ".." 和 "." 等相对路径
            }
        }

        /// <summary>
        /// 加载ab包的lua
        /// </summary>
        /// <param name="str"></param>
        private byte[] MyCustomLoaderAB(ref string filePath)
        {
            try
            {
                TextAsset textAsset = ABMgr.Instance.LoadResource<TextAsset>("lua", filePath + ".lua");
                if (textAsset == null)
                    Debug.Log("ab包中的lua文件重定向失败" + filePath);
                return textAsset.bytes;
            }
            catch (System.Exception ex)
            {
                Debug.LogWarning("加载资源时发生异常: " + ex.Message);
            }
            return null;
        }

        public void DoString(string str)
        {
            luaEnv.DoString(str);
        }

        public void DoFile(string path)
        {
            // requeire执行 默认通过Resources.load加载，无法识别lua，所以后续要加上txt
            luaEnv.DoString($"require('{path}')");
        }

        /// <summary>
        /// 释放垃圾
        /// </summary>
        public void Tick()
        {
            luaEnv.Tick();
        }

        public void Dispose()
        {
            luaEnv.Dispose();
            luaEnv = null;
        }


        #region   调用lua全局函数
        public void CallFunc(string funcName, params object[] args)
        {
            // luaEnv.Global.Get<CustomDelegate>(funcName)(args.Length, out int b);
            // Debug.Log($"b = {b}");
            var fn = luaEnv.Global.Get<Func<int, int>>(funcName);
            Debug.Log(fn(args.Length));
        }

        #endregion
    }
}